package com.siyu.core.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.siyu.common.hibernate3.Finder;
import com.siyu.common.hibernate3.HibernateBaseDao;
import com.siyu.common.page.Pagination;
import com.siyu.core.dao.SysUserDao;
import com.siyu.tickets.entity.SysUser;

@Repository
public class SysUserDaoImpl extends HibernateBaseDao<SysUser, Integer> implements SysUserDao {
	public SysUser getByUsername(String username) {
		return findUniqueByProperty("username", username);
	}

	public List<SysUser> getByEmail(String email) {
		return findByProperty("email", email);
	}

	public int countByEmail(String email) {
		String hql = "select count(*) from SysUser bean where bean.email=:email";
		Query query = getSession().createQuery(hql);
		query.setParameter("email", email);
		return ((Number) query.iterate().next()).intValue();
	}

	public Pagination getPage(int pageNo, int pageSize) {
		Criteria crit = createCriteria();
		Pagination page = findByCriteria(crit, pageNo, pageSize);
		return page;
	}

	public Pagination getPage(String username, String realname, String deptname, Integer typeId, Boolean activation,
			Integer orderBy, int pageNo, int pageSize) {
		Finder f = Finder.create("select bean from SysUser bean");
		f.append(" where 1=1");
		if (!StringUtils.isBlank(username)) {
			f.append(" and bean.username like :username");
			f.setParam("username", "%" + username + "%");
		}
		if (!StringUtils.isBlank(realname)) {
			f.append(" and bean.realname like :realname");
			f.setParam("realname", "%" + realname + "%");
		}
		if (!StringUtils.isBlank(deptname)) {
			f.append(" and bean.deptname like :deptname");
			f.setParam("deptname", "%" + realname + "%");
		}
		if (typeId != null) {
			f.append(" and bean.type.id=:typeId");
			f.setParam("typeId", typeId);
		}
		if (activation != null) {
			f.append(" and bean.activation=:activation");
			f.setParam("activation", activation);
		}
		f.append(" order by bean.id desc");
		return find(f, pageNo, pageSize);
	}

	public SysUser findById(Integer id) {
		SysUser entity = get(id);
		return entity;
	}

	public SysUser save(SysUser bean) {
		getSession().save(bean);
		return bean;
	}

	public SysUser deleteById(Integer id) {
		SysUser entity = super.get(id);
		if (entity != null) {
			getSession().delete(entity);
		}
		return entity;
	}

	@Override
	protected Class<SysUser> getEntityClass() {
		return SysUser.class;
	}
}